package com.didi.gulimall.config;

import com.alibaba.fastjson.JSON;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.factory.Factory.Payment;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.*;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.didi.gulimall.common.constant.OrderConstant;
import com.didi.gulimall.order.entity.OrderEntity;
import com.didi.gulimall.order.vo.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.time.LocalTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author 10626
 */
@Component
@Slf4j
@EnableConfigurationProperties(AlipayProperties.class)
public class AlipayTemplate {
    @Autowired
    private AlipayProperties alipayProperties;

    @Autowired
    private Config config;


    public String pay(OrderEntity order) throws Exception {

        Factory.setOptions(config);
        DecimalFormat df = new DecimalFormat("#.00");
        AlipayTradePagePayResponse response = Payment.Page().optional("timeout_express",alipayProperties.getTimeout())
                .pay("支付的订单号：" + order.getOrderSn(), order.getOrderSn(), df.format(order.getPayAmount()), alipayProperties.getReturnUrl());
        // 3. 处理响应或异常
        if (ResponseChecker.success(response)) {
            log.info("调用成功");
            return response.getBody();
        }
        return null;

    }

    public Boolean verifyNotify(PayAsyncVo payAsyncVo, HttpServletRequest request) throws Exception {
        Factory.setOptions(config);
        log.info("支付宝返回数据:{}", JSON.toJSONString(payAsyncVo));
        log.info("重试Id{}", payAsyncVo.getNotify_id());
        //验签
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        return Payment.Common().verifyNotify(params);
    }

    public Boolean query(String orderSn) throws Exception {
        Factory.setOptions(config);
        //查询
        AlipayTradeQueryResponse query = Payment.Common().query(orderSn);
        if (ResponseChecker.success(query)) {
            log.info("{}的查询结果为:{}", orderSn, JSON.toJSON(query));
            return query.getTradeStatus().equals(OrderConstant.ALIPAY_PAID_SUCCESSFULLY) || query.getTradeStatus().equals(OrderConstant.ALIPAY_PAID_TRADING_CLOSED);
        } else {
            log.error("{}的查询失败原因为:{}", orderSn, JSON.toJSON(query));
        }
        return false;
    }

    public void closed(String orderSn) throws Exception {
        Factory.setOptions(config);
        //关单
        AlipayTradeCloseResponse close = Payment.Common().close(orderSn);
        if (ResponseChecker.success(close)) {
            log.info("{}的关闭结果为:{}", orderSn, JSON.toJSON(close));
        } else {
            log.error("{}关单失败 结果为:{}", orderSn, JSON.toJSON(close));
        }
    }
    public void cancel(String orderSn)throws Exception {
        Factory.setOptions(config);
        //撤销
        AlipayTradeCancelResponse cancel = Payment.Common().cancel(orderSn);
        if (ResponseChecker.success(cancel)) {
            log.info("{}的关闭结果为:{}", orderSn, JSON.toJSON(cancel));
        } else {
            log.error("{}关单失败 结果为:{}", orderSn, JSON.toJSON(cancel));
        }
    }
    public void refund(OrderEntity orderEntity) throws Exception {
        Factory.setOptions(config);
        DecimalFormat df = new DecimalFormat("#.00");
        //查询
        AlipayTradeRefundResponse refund = Payment.Common().refund(orderEntity.getOrderSn(), df.format(orderEntity.getPayAmount()));
        if (ResponseChecker.success(refund)) {
            log.info("{}的关闭结果为:{}", orderEntity.getOrderSn(), JSON.toJSON(refund));
        }
    }

}
